import Taro, {Component} from '@tarojs/taro'
import {View, Text, Button} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {getTopicInfo, admireTopic, sendReply} from '../../actions/topic'
import TopicInfo from '../../components/topicinfo/topicinfo'
import Replies from '../../components/topicinfo/replies'
import ReplyContent  from '../../components/topicinfo/replycontent'

import './index.scss'

@connect((store)=> {
  return {user: store.user, topicInfo: store.topicList.topicInfo, replies: store.topicList.replies, admireState: store.topicList.admireState}
}, (dispatch) => {
  return {
    getTopicInfo(params) {
      dispatch(getTopicInfo(params))
    },
    admireTopic (params) {
      dispatch(admireTopic(params))
    }
  }
})

class Detail extends Component {
  state = {
    showReplyContent: false
  }
  componentWillMount () {
    this.getDetail()
  }
  getDetail () {
    console.log(this.$router.params.topicid);
    let {user} = this.props
    this.props.getTopicInfo({
      id: this.$router.params.topicid,
      mdrender: true,
      accesstoken: user.accessToken
    })
  }
  admire (reply) {
    console.log('id = ', this.props.user.accessToken);
    let params = {id: reply.id, accesstoken: this.props.user.accessToken}
    this.props.admireTopic && this.props.admireTopic(params)
  }
  componentWillReceiveProps(nextProps) {
    if(this.props.admireState != nextProps.admireState) {
      this.getDetail()
    }
  }
  Reply () {
    this.setState({
      showReplyContent: true
    })
  }
  async btnOk (content) {
    let {user} = this.props
    let {curReply} = this.state
    let reply_id = curReply ? curReply.id : null
    let preName = curReply ? '@' + curReply.author.loginname + '  ': ''
    let params = {content: preName + content,topicid: this.$router.params.topicid, accesstoken: user.accessToken, reply_id}
    // let res = await sendReply(params)
    // if(res.success) {
    //   this.getDetail()
    // }
    console.log(content)
    sendReply(params).then(res => {
      if(res.success) {
          this.getDetail()
        }
    })
  }
  btnCancel () {
    this.setState({
      showReplyContent: false
    })
  }
  toReply (curReply) {
    this.setState({
      curReply, showReplyContent: true
    })
  }

  render () {
   let {topicInfo, replies} = this.props
   let {showReplyContent} = this.state
    return (
      <View className='detail-wrap'>
        {
          showReplyContent ? <ReplyContent onBtnOk={this.btnOk.bind(this)} onBtnCancel={this.btnCancel.bind(this)} /> : null
        }
        <TopicInfo  topicInfo={topicInfo} />
        <Replies replies={replies} onAdmire={this.admire.bind(this)} onToReply={this.toReply.bind(this)} />
        <Button className='replyBtn' onClick={this.Reply.bind(this)}>回复</Button>
      </View>
    )
  }
}

export default Detail